<template>
	<view class="content">
		<uni-search-bar placeholder="请输入关键词搜索" cancelButton="none" radius="50" @confirm="search"
			@clear="clearKeyword()" />
		<view v-if="blogs.length==0" class="none">
			<image src="../../static/icons/nodata.png" mode="" class="logo"></image>
			<text>暂无数据</text>
		</view>
		<view v-else class="item-container" v-for="(item,index) in blogs" :key="item.id" @click.stop="gotoDetail(item.id)">
			<!-- 标题 -->
			<text class="item-title">{{item.title}}</text>
			<!-- 文本内容 -->
			<rich-text :nodes="item.description" class="item-desc"></rich-text>
			<!-- 图片 -->
			<image :src="item.picture" mode="widthFix" class="item-pic"></image>
			<!-- <image src="../../static/icons/ic_share.png" mode="aspectFill" class="share"></image> -->
			<!-- 分享 -->
			<text @click.stop="popSheet(item.id)" class="iconfont icon-caret-down share"></text>
			<!-- tag -->
			<view>
				<!-- 内层循环 -->
				<text v-for="(tag,idx) in item.tags" :key="idx" class="item-tag">{{tag}}</text>
			</view>
			<!-- 用户头像 -->
			<image :src="item.user.avatar" mode="aspectFill" class="img-head" @click.stop="clickShowUser(item.user)"></image>
				<!-- <image :src="item.user.avatar" mode="aspectFill" class="img-head"></image> -->
			<view class="icon-container">
				<!-- 点赞  由于changeGood在gotoDetail的内部，会引起事件冒泡，所以为了独立两个事件，在内侧的事件加上stop-->
				<image @click.stop="changeGood(item.id,true)" v-if="good_ids.indexOf(item.id) < 0"
					src="../../static/icons/ic_good.png" class="icon"></image>
				<image @click.stop="changeGood(item.id,false)" v-else src="../../static/icons/ic_good_fill.png"
					class="icon"></image>
				<text class="icon-text">{{item.good}}</text>
				<!--  评论 -->
				<image src="../../static/icons/ic_comment.png" class="icon"></image>
				<text class="icon-text">{{item.comments.length}}</text>
				<!--  阅览 -->
				<image src="../../static/icons/ic_count.png" class="icon"></image>
				<text class="icon-text">{{item.readCount}}</text>
			</view>
		</view>
     
		<dialog-shell ref="shell" title="用户描述" @confirm = "confirmInfo">
			<text style="padding: 10rpx;font-size: 28rpx;">{{userDesc}}</text>
		</dialog-shell>
	</view>
</template>



<script>
	let page = 0;
	let size = 3;
	// 博客列表的本地存储值
	let key_blogs = "blogs"
	
	export default {
		data() {
			return {
				blog: [],
				blogs: [],
				count: -1,
				isBottom: false, //底部显示
				searching: false,
				good_ids: [], //点赞
				userDesc: [],
				show: false
			}
		},
		//加载时执行
		onLoad() {
			this.$noti.add(this.$params.noti_refresh_count, this.notifyRefreshCount, this)
			this.$noti.add(this.$params.noti_refresh_comment, this.notifyRefreshComment, this)
			//缓存点赞数据
			let ids = uni.getStorageSync(this.$params.key_good_ids)
			if (ids) {
				this.good_ids = ids
			}
			//缓存blogs分页数据
			let blogs = uni.getStorageSync("key_blogs")
			if (blogs) { //如果有本地数据使用本地数据
				this.blogs = blogs;
				this.count = blogs.length
			} else {
				this.getPagedBlogs()//没有则使用服务器数据
			}
			//获取页面数据
			// this.getPagedBlogs()		
		},
		//移除卸载
		onUnload() {
			this.$noti.remove(this.$params.noti_refresh_count, this)
			this.$noti.remove(this.$params.noti_refresh_comment, this)//移除通知
		},
		// 下拉刷新
		onPullDownRefresh() {
			page = 0 //页清零
			this.blogs = [] //数据清零
			this.count - 1 //初值
			this.getPagedBlogs() //再次执行方法
		},
		// 到底部加载下一页
		onReachBottom() {
			if (this.searching || this.blogs.length == this.count) {
				uni.showToast({
					title: "我是有底线的"
				})
				return
			}
			page += 1
			this.getPagedBlogs()
		},


		methods: {
			notifyRefreshComment(info){
				let id = info.id
				let comment = info.comment
				let index =this.blogs.findIndex(obj=>obj.id===id);
				this.blogs[index].comments=comment
				console.log(info);
			},

			//详情页跳转
			gotoDetail(id) {
				uni.navigateTo({
					url: '../blog/blog?id=' + id,
					success: res => {},
					fail: () => {},
					complete: () => {}
				});
			},

			notifyRefreshCount(info) {
				let id = info.id
				let count = info.count
				this.RefreshReadCount(info, id, info.count)

			},

			//浏览次数增加
			RefreshReadCount(id, count) {
				this.blogs.forEach(b => {
						if (b.id == id) {
							b.ReadCount = count
						}
					}),
					console.log("刷新了列表页");
			},

			//点赞&&取消点赞方法
			changeGood(id, isGood) {
				//同步到服务器，并且取最新数据
				this.$refs.shell.show()
				let url = this.$params.host
				let action = isGood ? this.$params.action_good : this.$params.action_del_good
				url += action
				let data = {
					"id": id
				}
				this.$request.postParam(url, data, res => {
					this.blogs.forEach(blog => {
						if (blog.id == id) {
							blog.good = res.data
						}
					})
					if (isGood) {
						this.good_ids.push(id)
						//另一个方法：
						// this.good_ids=this.good_ids.concat(id)
						//[a,b,c[d,e]]可以两个数组
					} else {
						//取消点赞//shift删除第一个元素，pop删除最后一个元素，splice删除指定元素
						//pop把最后一个元素替换要删除的元素，然后pop[1,2,3,4,5]
						//数组较大且顺序不影响程序功能时，可提高时效性、性能
						let index = this.good_ids.indexOf(id)

						this.$utli.remove(this.good_ids, index)
					}
					uni.setStorageSync(this.$params.key_good_ids, this.good_ids)
				}, () => {})
			},


			getPagedBlogs() {
				console.log("分页请求开始")
				uni.setStorageSync("test", 123)
				if (this.blogs.length == this.count) {
					uni.showToast({
						title: "加载完成",

					})
					return
				}

				let header = {
					"content-type": "application/json;charset=UTF-8",
					"page": page,
					"size": size
				}
				this.$request.getWithHeader(this.$params.host + this.$params.action_blogs_page, header, res => {
					res.data.forEach(blog => {
						if (!blog.picture.startsWith("http")) {
							blog.picture = this.$params.host + blog.picture
						}
						blog.user.avatar = this.$params.host + blog.user.avatar
					})
					this.blogs = [...this.blogs, ...res.data]

					//保存最新的blogs列表
					uni.setStorageSync(key_blogs, this.blogs)

					this.count = parseInt(res.message)
				}, () => {
					//停止刷新 否则会一直进行刷新
					uni.stopPullDownRefresh()
				})
			},
			// 获取搜索框内容并发请求
			search(e) {
				// console.log(e)
				let kw = e.value
				// 判断搜索框内容是否为空
				if (kw.length > 0) {
					// 	//清空列表数据
					this.blogs = [];
					// 	// 重置count
					this.count = -1;
					// 	// 发起请求 要在常量文件中添加搜索地址 使用get方法发起请求 处理请求结果 
					this.$request.get(this.$params.host + this.$params.action_blogs_search + kw, res => {
						res.data.forEach(blog => {
							if (!blog.picture.startsWith('http')) {
								blog.picture = this.$params.host + blog.picture
							}
							blog.user.avatar = this.$params.host + blog.user.avatar
						})
						this.blogs = [...this.blogs, ...res.data]
					}, () => {
						this.getPagedBlogs = true
					})

				}
			},
			clearKeyword() {
				//初始化blogs
				this.blogs = []
				//初始化分页
				page = 0
				//分页请求
				this.getPagedBlogs()
				//结束搜索
				this.searching = false

			},
			popSheet(id) {
				uni.showActionSheet({
					itemList: ['删除', '收藏'],
					success: res => {
						if (res.tapIndex == 0) {
							//删除
							uni.showModal({
								title: '删除blog',
								content: '确认删除吗',
								showCancel: true,
								cancelText: '算了',
								confirmText: '删除',

								success: res => {
									if (res.confirm) {
										this.deleteBlog(id)
									}

								},
								fail: () => {},
								complete: () => {}
							});
						} else {
							// 收藏
							uni.showToast({
								title: '收藏成功'
							});
						}
					},
					fail: () => {},
					complete: () => {}
				});
			},
			deleteBlog(id) {
				uni.showToast({
					title: '请先登录'
				});
			},
			//提示框弹出用户信息
			clickShowUser(user) {
				this.userDesc = "作者" + user.nickName + "\n联系方式:" + user.email;
				this.$refs.shell.show()
			},
			confirmInfo() {
				console.log("emit");
			},



		}
	}
</script>

<style>
	@import url('../../common/iconfont.css');
	@import url('index.css');
</style>
